<template>
  <div class="small-line-chart" :style="customStyle">
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>
<script>
import * as echarts from "echarts";
export default {
  name: "SmallLineChart",
  props: {
    // 可自定义的数据属性
    chartData: {
      type: Array,
      default: () => [],
    },
    // 可自定义的颜色
    lineColor: {
      type: String,
      default: "#348CF8",
    },
    // 是否显示填充区域
    showArea: {
      type: Boolean,
      default: true,
    },
    // 是否显示数据点
    showSymbol: {
      type: Boolean,
      default: false,
    },
    // 是否显示数值标签
    showLabel: {
      type: Boolean,
      default: true,
    },
    // 标签字体大小
    labelFontSize: {
      type: Number,
      default: 10,
    },
    customStyle: {
      type: Object,
      default: () => ({}),
    },
    // 添加柱状图位置控制属性（新添加）
    gridTop: {
      type: String,
      default: "0",
    },
    gridRight: {
      type: String,
      default: "0",
    },
    gridBottom: {
      type: String,
      default: "0",
    },
    gridLeft: {
      type: String,
      default: "0",
    },
  },
  data() {
    return {
      chart: null,
      resizeTimer: null,
    };
  },
  // 添加watch监听barWidth变化，实现动态更新
  watch: {
    // 添加grid位置属性的watch（新添加）
    gridTop: {
      handler(newValue) {
        this.updateGridPosition("top", newValue);
      },
    },
    gridRight: {
      handler(newValue) {
        this.updateGridPosition("right", newValue);
      },
    },
    gridBottom: {
      handler(newValue) {
        this.updateGridPosition("bottom", newValue);
      },
    },
    gridLeft: {
      handler(newValue) {
        this.updateGridPosition("left", newValue);
      },
    },
  },
  mounted() {
    this.initChart();
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    if (this.resizeTimer) {
      clearTimeout(this.resizeTimer);
    }
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
  watch: {
    chartData: {
      handler() {
        this.updateChart();
      },
      deep: true,
    },
  },
  methods: {
    // 生成默认数据
    generateDefaultData() {
      return [
        12, 19, 16, 18, 24, 26, 22, 18, 21, 16, 28, 24, 20, 22, 15, 18, 21, 24,
        19, 16, 22, 20, 18, 25,
      ];
    },

    initChart() {
      if (!this.$refs.chartRef) return;

      // 初始化图表
      this.chart = echarts.init(this.$refs.chartRef);

      this.updateChart();
    },

    updateChart() {
      if (!this.chart) return;

      // 使用传入的数据或生成默认数据
      const dataValues =
        this.chartData.length > 0 ? this.chartData : this.generateDefaultData();

      // 保存this.lineColor到变量，避免在回调函数中丢失上下文
      const lineColor = this.lineColor;

      // 图表配置
      const option = {
        tooltip: {
          show: true, // 显示tooltip
          trigger: "axis",
          backgroundColor: "rgba(0, 0, 0, 0.7)",
          borderColor: lineColor,
          borderWidth: 1,
          textStyle: {
            color: "#fff",
            fontSize: 12,
          },
          padding: 8,
          formatter: function (params) {
            return params[0].value;
          },
          axisPointer: {
            type: "line",
            lineStyle: {
              color: lineColor,
              width: 1,
              type: "dashed",
            },
          },
        },
        grid: {
          top: this.showLabel ? 20 : 0, // 有标签时增加顶部边距
          // 使用动态传入的位置属性
          right: this.gridRight,
          bottom: this.gridBottom,
          left: this.gridLeft,
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: dataValues.map((_, index) => index),
          show: false, // 不显示x轴
        },
        yAxis: {
          type: "value",
          show: false, // 不显示y轴
        },
        series: [
          {
            type: "line",
            data: dataValues,
            smooth: true, // 平滑曲线
            symbol: this.showSymbol ? "circle" : "none", // 数据点样式
            symbolSize: this.showSymbol ? 4 : 0, // 数据点大小
            lineStyle: {
              color: lineColor,
              width: 2,
            },
            itemStyle: {
              color: lineColor,
            },
            areaStyle: this.showArea
              ? {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: lineColor + "88", // 半透明颜色
                    },
                    {
                      offset: 1,
                      color: lineColor + "11", // 几乎透明的颜色
                    },
                  ]),
                }
              : {},
            // 显示数值标签 - 只显示当天数据（最后一个数据点）
            label: {
              show: this.showLabel,
              position: "top",
              color: lineColor,
              fontSize: this.labelFontSize,
              fontWeight: "bold",
              formatter: function (params) {
                // 只显示最后一个数据点的标签
                if (params.dataIndex === dataValues.length - 1) {
                  return params.value;
                }
                return "";
              },
              distance: 5,
              // 不自动显示最小最大值标签
              showMinLabel: false,
              showMaxLabel: false,
            },
          },
        ],
      };

      // 设置配置
      this.chart.setOption(option);
    },

    handleResize() {
      if (this.resizeTimer) {
        clearTimeout(this.resizeTimer);
      }
      this.resizeTimer = setTimeout(() => {
        if (this.chart) {
          this.chart.resize();
        }
      }, 100);
    },
  },
};
</script>
<style scoped>
.small-line-chart {
  width: 100%;
  height: 100px;
}

.chart-container {
  width: 100%;
  height: 100%;
}
</style>
